#include<stdio.h>
#include<sys/types.h>
#include<nlm/sys/socket.h>
#include<nlm/sys/bsdskt.h>
#include<netinet/in.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/time.h>

#define TIMEOUT_SEC 10
#define TIMEOUT_USEC 0
#define LISTEN_PORT 2000

int NLM_Exiting = FALSE;

void main(void)
{
	int serverSocket;
	int clientSocket;
	int sizeofClientAddr;
	char buff[300];
	struct sockaddr_in serverAddr, clientAddr;
	fd_set fd; 
	struct timeval tv;
	int rcode;

	if(( serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == (-1)){
		perror("socket");
		goto END_ERR;
	}

	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(LISTEN_PORT);
	serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);

	if(( bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr))) == (-1)){
		perror("bind");
		goto END_ERR;
	}

	if(( listen(serverSocket, 0)) == (-1)){
		perror("listen");
		goto END_ERR;
	}

	while(!NLM_Exiting)
	{
		sizeofClientAddr = sizeof(clientAddr);
		FD_ZERO(&fd);
		FD_SET(serverSocket, &fd);
		tv.tv_sec = TIMEOUT_SEC;
		tv.tv_usec = TIMEOUT_USEC;

		rcode = select(FD_SETSIZE, &fd, NULL, NULL, &tv);
		
		printf("rcode = %d\r\n", rcode);

		if(rcode == 1){

			if(( clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddr, &sizeofClientAddr)) == (-1)){
				perror("accept");
				goto END_ERR;
			}

			if(( recv(clientSocket, &buff, sizeof(buff), 0)) == (-1)){
				perror("recv");
				goto END_ERR;
			}

			printf("recv: %s\r\n", buff);
	

			if(( send(clientSocket, &buff, strlen(buff), 0)) == (-1)){
				perror("send");
				goto END_ERR;
			}
				
			close(clientSocket);
		}//end if(rcode == 1)
	}//end while(!NLM_Exiting)
END_ERR:
	close(clientSocket);
	close(serverSocket);
}